// Background script for QKL Wallet Extension
import { WalletManager } from '../core/WalletManager';
import { NetworkManager } from '../core/NetworkManager';
import { TokenManager } from '../core/TokenManager';

class WalletBackground {
  private walletManager: WalletManager;
  private networkManager: NetworkManager;
  private tokenManager: TokenManager;

  constructor() {
    this.walletManager = new WalletManager();
    this.networkManager = new NetworkManager();
    this.tokenManager = new TokenManager();
    
    this.setupMessageHandlers();
    this.setupTabHandlers();
  }

  private setupMessageHandlers(): void {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      this.handleMessage(message, sender, sendResponse);
      return true; // 保持消息通道开放
    });
  }

  private setupTabHandlers(): void {
    // 监听标签页更新
    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
      if (changeInfo.status === 'complete' && tab.url) {
        this.injectContentScript(tabId);
      }
    });
  }

  private async injectContentScript(tabId: number): void {
    try {
      await chrome.scripting.executeScript({
        target: { tabId },
        files: ['dist/inject.js']
      });
    } catch (error) {
      console.log('无法注入内容脚本:', error);
    }
  }

  private async handleMessage(message: any, sender: chrome.runtime.MessageSender, sendResponse: (response?: any) => void): Promise<void> {
    try {
      switch (message.type) {
        case 'GET_ACCOUNTS':
          const accounts = this.walletManager.getAccounts();
          sendResponse({ success: true, data: accounts });
          break;

        case 'GET_CURRENT_ACCOUNT':
          const currentAccount = this.walletManager.getCurrentAccount();
          sendResponse({ success: true, data: currentAccount });
          break;

        case 'UNLOCK_WALLET':
          const { address, password } = message.data;
          const unlocked = await this.walletManager.unlockWallet(address, password);
          sendResponse({ success: unlocked });
          break;

        case 'SEND_TRANSACTION':
          const { to, amount, pwd } = message.data;
          const txHash = await this.walletManager.sendTransaction(to, amount, pwd);
          sendResponse({ success: true, data: txHash });
          break;

        case 'GET_BALANCE':
          const { accountAddress } = message.data;
          const balance = await this.walletManager.getBalance(accountAddress);
          sendResponse({ success: true, data: balance });
          break;

        case 'GET_NETWORKS':
          const networks = this.networkManager.getNetworks();
          sendResponse({ success: true, data: networks });
          break;

        case 'SWITCH_NETWORK':
          const { network } = message.data;
          this.networkManager.switchNetwork(network);
          sendResponse({ success: true });
          break;

        case 'GET_TOKENS':
          const tokens = this.tokenManager.getAllTokens();
          sendResponse({ success: true, data: tokens });
          break;

        case 'REQUEST_PERMISSION':
          await this.handlePermissionRequest(message.data, sender, sendResponse);
          break;

        default:
          sendResponse({ success: false, error: '未知消息类型' });
      }
    } catch (error) {
      sendResponse({ success: false, error: error.message });
    }
  }

  private async handlePermissionRequest(data: any, sender: chrome.runtime.MessageSender, sendResponse: (response?: any) => void): Promise<void> {
    const { origin, method, params } = data;
    
    // 创建权限请求通知
    const notificationId = `permission_${Date.now()}`;
    
    await chrome.notifications.create(notificationId, {
      type: 'basic',
      iconUrl: 'assets/icon48.png',
      title: 'QKL钱包权限请求',
      message: `${origin} 请求连接到您的钱包`
    });

    // 这里应该显示权限确认弹窗
    // 为了演示，我们直接批准请求
    sendResponse({ success: true, approved: true });
  }

  // 处理DApp连接请求
  public async handleDAppConnection(origin: string, method: string, params: any[]): Promise<any> {
    switch (method) {
      case 'eth_requestAccounts':
        return await this.handleRequestAccounts();
      
      case 'eth_accounts':
        return await this.handleGetAccounts();
      
      case 'eth_sendTransaction':
        return await this.handleSendTransaction(params[0]);
      
      case 'eth_sign':
        return await this.handleSignMessage(params[0], params[1]);
      
      case 'personal_sign':
        return await this.handlePersonalSign(params[0], params[1]);
      
      case 'eth_signTypedData':
        return await this.handleSignTypedData(params[0], params[1]);
      
      case 'wallet_switchEthereumChain':
        return await this.handleSwitchChain(params[0]);
      
      case 'wallet_addEthereumChain':
        return await this.handleAddChain(params[0]);
      
      default:
        throw new Error(`不支持的方法: ${method}`);
    }
  }

  private async handleRequestAccounts(): Promise<string[]> {
    const currentAccount = this.walletManager.getCurrentAccount();
    if (!currentAccount) {
      throw new Error('请先解锁钱包');
    }
    return [currentAccount.address];
  }

  private async handleGetAccounts(): Promise<string[]> {
    const accounts = this.walletManager.getAccounts();
    return accounts.map(account => account.address);
  }

  private async handleSendTransaction(transaction: any): Promise<string> {
    // 这里需要用户确认交易
    // 为了演示，我们直接发送
    const currentAccount = this.walletManager.getCurrentAccount();
    if (!currentAccount) {
      throw new Error('请先解锁钱包');
    }
    
    // 这里应该显示交易确认弹窗
    // 暂时返回模拟的交易哈希
    return '0x' + Math.random().toString(16).substr(2, 64);
  }

  private async handleSignMessage(address: string, message: string): Promise<string> {
    // 实现消息签名
    return '0x' + Math.random().toString(16).substr(2, 64);
  }

  private async handlePersonalSign(message: string, address: string): Promise<string> {
    // 实现个人签名
    return '0x' + Math.random().toString(16).substr(2, 64);
  }

  private async handleSignTypedData(address: string, typedData: any): Promise<string> {
    // 实现结构化数据签名
    return '0x' + Math.random().toString(16).substr(2, 64);
  }

  private async handleSwitchChain(chainParams: any): Promise<null> {
    const network = this.networkManager.getNetworkByChainId(parseInt(chainParams.chainId, 16));
    if (network) {
      this.networkManager.switchNetwork(network);
    } else {
      throw new Error('不支持的链');
    }
    return null;
  }

  private async handleAddChain(chainParams: any): Promise<null> {
    const newNetwork = {
      name: chainParams.chainName,
      chainId: parseInt(chainParams.chainId, 16),
      rpcUrl: chainParams.rpcUrls[0],
      blockExplorer: chainParams.blockExplorerUrls?.[0] || '',
      nativeCurrency: chainParams.nativeCurrency
    };
    
    this.networkManager.addCustomNetwork(newNetwork);
    return null;
  }
}

// 初始化后台脚本
new WalletBackground();
